package net.easyjava.base.service.mongodb.impl;

import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.QueryResults;
import com.google.code.morphia.query.UpdateOperations;
import net.easyjava.base.bean.mongodb.RequestLogBean;
import net.easyjava.base.dao.mongodb.RequestLogDao;
import net.easyjava.base.service.mongodb.RequestLogService;
import net.easyjava.tools.page.Page;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by wenxiaoning on 15/12/20.
 */
@Component
public class RequestLogServiceImpl implements RequestLogService {
    @Resource
    private RequestLogDao requestLogDao;
    /**
     * 保存request日志
     *
     * @return
     */
    @Override
    public RequestLogBean save(RequestLogBean requestLogBean) {
        return find(requestLogDao.save(requestLogBean).getId().toString());
    }

    /**
     * 查询一条request日志记录
     * @param id
     * @return
     */
    @Override
    public RequestLogBean find(String id) {
        return requestLogDao.findOne("id",id);
    }

    /**
     * 修改日志
     *
     * @param requestLogBean
     * @return
     */
    @Override
    public RequestLogBean update(RequestLogBean requestLogBean) {
        UpdateOperations<RequestLogBean> operations = requestLogDao.createUpdateOperations();

        if(requestLogBean.getTotalTime()>0){
            operations.set("totalTime", requestLogBean.getTotalTime());
        }
        requestLogDao.updateFirst(requestLogDao.createQuery().filter("id", requestLogBean.getId()), operations);
        return find(requestLogBean.getId());
    }

    /**
     * 查询request日志列表
     *
     * @return
     */
    @Override
    public Page<RequestLogBean> find(int pageNum,int pageSize) {
        Query<RequestLogBean> query = requestLogDao.createQuery().batchSize((pageNum-1)*pageSize).limit(pageSize).order("-createTime");
        QueryResults<RequestLogBean> results = requestLogDao.find(query);
        return new Page<RequestLogBean>(results.asList(), (int) results.countAll(),pageNum);
    }
}
